package com.mlink.ai.chat.ui.viewmodel

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.local.ChatDatabase
import com.mlink.ai.chat.local.entity.ChatMessageEntity
import com.mlink.ai.chat.ui.adapter.ChatItem
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

class RecentViewModel : ViewModel() {

    val historyMessage = MutableLiveData<MutableList<ChatMessageEntity>>() // 暂时先不考虑保存状态

    fun getAllHistoryMessage() {
        viewModelScope.launch(Dispatchers.IO) {
            runCatching {
                ChatDatabase.getInstance(AiChatApplication.app).chatMessageDao().getAllMessages()
            }.onSuccess {
                withContext(Dispatchers.Main) {
                    historyMessage.value = it.toMutableList()
                }
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun insertHistoryMessage(entity: ChatMessageEntity?) {
        entity ?: return
        GlobalScope.launch(Dispatchers.IO) {
            runCatching {
                ChatDatabase.getInstance(AiChatApplication.app).chatMessageDao()
                    .insertMessage(entity)
                ChatMessageEntity.removeTempData()
                ChatMessageEntity.removeTempPic()
                val list = ChatDatabase.getInstance(AiChatApplication.app).chatMessageDao()
                    .getAllMessagesWithoutLimit()
                if (list.size > 12) {
                    list.subList(12, list.size).forEach {
                        deleteHistoryMessage(it)
                    }
                }
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    fun deleteHistoryMessage(entity: ChatMessageEntity) {
        GlobalScope.launch(Dispatchers.IO) {
            kotlin.runCatching {
                ChatDatabase.getInstance(AiChatApplication.app).chatMessageDao()
                    .deleteMessage(entity)
            }.onSuccess {
                getAllHistoryMessage()
                runCatching {
                    val jsonString = entity.messageContent
                    val typeToken: TypeToken<List<ChatItem>> =
                        object : TypeToken<List<ChatItem>>() {}
                    val data = Gson().fromJson<List<ChatItem>>(jsonString, typeToken.type)
                    data.forEach {
                        val path = it.content?.imagePath
                        if (!TextUtils.isEmpty(path)) {
                            val file = File(path!!)
                            file.delete()
                        }
                    }
                }
            }
        }
    }

}